package com.huawei.leetcode;

import java.util.ArrayList;
import java.util.List;

public class Code17 {
    public static void main(String[] args) {

    }

    public List<String> letterCombinations(String digits) {
        List<String> ans = new ArrayList<>();
        if (digits.length() == 0) {
            return ans;
        }
        String[] numbers = new String[10];
        numbers[2] = "abc";
        numbers[3] = "def";
        numbers[4] = "ghi";
        numbers[5] = "jkl";
        numbers[6] = "mno";
        numbers[7] = "pqrs";
        numbers[8] = "tuv";
        numbers[9] = "wxyz";


        if (digits.length() == 1) {
            char[] chars = numbers[Integer.valueOf(digits)].toCharArray();
            for (char aChar : chars) {
                ans.add(String.valueOf(aChar));
            }
        } else if (digits.length() == 2) {
            String str1 = numbers[Integer.parseInt(String.valueOf(digits.charAt(0)))];
            String str2 = numbers[Integer.parseInt(String.valueOf(digits.charAt(1)))];
            ans = parseAns(ans, str1, str2);
        } else if (digits.length() == 3) {
            String str1 = numbers[Integer.parseInt(String.valueOf(digits.charAt(0)))];
            String str2 = numbers[Integer.parseInt(String.valueOf(digits.charAt(1)))];
            String str3 = numbers[Integer.parseInt(String.valueOf(digits.charAt(2)))];
            List<String> list = parseAns(ans, str1, str2);
            char[] chars3 = str2.toCharArray();
            for (int i = 0; i < list.size(); i++) {
                for (int j = 0; j < chars3.length; j++) {
                    ans.add(list.get(i) + chars3[j]);
                }
            }
        } else {
            String str1 = numbers[Integer.parseInt(String.valueOf(digits.charAt(0)))];
            String str2 = numbers[Integer.parseInt(String.valueOf(digits.charAt(1)))];
            String str3 = numbers[Integer.parseInt(String.valueOf(digits.charAt(2)))];
            String str4 = numbers[Integer.parseInt(String.valueOf(digits.charAt(3)))];
            List<String> list1 = parseAns(ans, str1, str2);
            List<String> list2 = parseAns(ans, str3, str4);
            for (int i = 0; i < list1.size(); i++) {
                for (int j = 0; j < list2.size(); j++) {
                    ans.add(list1.get(i) + list2.get(2));
                }
            }
        }
        return ans;
    }

    private List<String> parseAns(List<String> ans, String str1, String str2) {
        char[] chars1 = str1.toCharArray();
        char[] chars2 = str2.toCharArray();

        for (int i = 0; i < chars1.length; i++) {
            for (int j = 0; j < chars2.length; j++) {
                ans.add(String.valueOf(chars1[i]) + chars2[j]);
            }
        }
        return ans;
    }
}
